package com.ding.controller;

import com.ding.entity.RuleInfo;
import com.ding.service.RuleService;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.builder.Results;
import org.kie.api.io.ResourceType;
import org.kie.internal.utils.KieHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ding
 * @date 2021/6/9 11:53
 */

@Slf4j
@RestController
@RequestMapping("rule")
public class RuleController {

    @Autowired
    private RuleService ruleService;


    @GetMapping
    public List<RuleInfo> getRuleList() {
        return ruleService.getAllRules();
    }

    @PostMapping
    public String addRule(String rule) {
        ruleService.addRule(rule);
        return "新增规则成功";
    }

    @DeleteMapping
    public String deleteRule(Long id) {
        ruleService.deleteRule(id);
        return "删除规则成功";
    }

    @PutMapping
    public String updateRule(RuleInfo ruleInfo) {
        ruleService.update(ruleInfo);
        return "更新规则成功";
    }

    @PostMapping("verify")
    public Results verify(@RequestParam("rule") String rule) {
        log.error(rule);
        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(rule, ResourceType.DRL);
        Results verify = kieHelper.verify();
        return verify;

    }


    @GetMapping("verifyAll")
    public Results verifyAll() {
        List<RuleInfo> allRules = this.ruleService.getAllRules();
        KieHelper kieHelper = new KieHelper();
        for (RuleInfo ruleInfo : allRules) {
            log.error(ruleInfo.getContent());
            kieHelper.addContent(ruleInfo.getContent(), ResourceType.DRL);
        }
        return kieHelper.verify();
    }
}
